package com.example.project01.service;

import com.example.project01.model.Banner;
import com.leon.model.Model;
import com.leon.model.Pageable;
import com.leon.model.Paged;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
@AllArgsConstructor
public class BannerService {

    private final SqlSession sqlSession;

    public Paged<Banner> banners(Pageable pageable, String module, String type, String status, Timestamp createdAt, String name, String language) {
        int total = sqlSession.selectOne("banner.wholeBanner");
        log.info("获取查询条数{}条", total);
        Map<String,Object> map = pageable.asMap().put("module", module).put("type", type).put("status", status).put("createdAt", createdAt).put("name", name).put("language", language).end();
        List<Banner> banners = Model.converts(Banner::new, sqlSession.selectList("banner.listBanner", map));
        log.info("查询到数据{}", banners);
        return Paged.of(banners, total);
    }

    public int save(Banner banner, Boolean update) {
        if (update) {
            banner.isModule(banner.getModule());
            banner.isType(banner.getType());
            banner.isStatus(banner.getStatus());
            log.info("修改数据{}", banner);
            return sqlSession.update("banner.insertBanner", banner.toMap());
        }
        if (Objects.isNull(banner.getUrl())) {
            banner.setType(Banner.TypeEnum.NO_ADVERT.name());
        } else {
            banner.setType(Banner.TypeEnum.ADVERT.name());
        }
        banner.isModule(banner.getModule());
        banner.setStatus(Banner.StatusEnum.USING.name());
        log.info("新增数据{}", banner);
        return sqlSession.insert("banner.insertBanner",banner.toMap());
    }

    public void deleteBanner(Long id) {
        sqlSession.update("banner.deleteBanner", id);
        log.info("修改ID为{}状态", id);
    }

    public Paged<Banner> bannersList(Pageable pageable) {
        int total = sqlSession.selectOne("banner.appBanner");
        List<Banner> banners = Model.converts(Banner::new, sqlSession.selectList("banner.appListBanner", pageable.toMap()));
        return Paged.of(banners, total);
    }
}
